package com.tengfei.main;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author feige
 * @version v1.0
 * @date 2022-09-21-10:07
 * @description Cglib动态代理
 */
public class CglibDynamicProxy {

    public static void main(String[] args) {
        MsgService msgService = (MsgService) CglibProxyFactory.getProxy(MsgService.class);
        msgService.send("发送短信哈...");
    }
}

class MsgService {
    public String send(String msg) {
        System.out.println("发送短信：" + msg);
        return msg;
    }
}

class DebugMethodInterceptor implements MethodInterceptor {

    /**
     * @param o           被代理的对象
     * @param method      被代理拦截的方法
     * @param args        方法入参
     * @param methodProxy 代理执行方法
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("短信发送前：" + method.getName());
        Object res = methodProxy.invokeSuper(o, args);
        System.out.println("方法执行后：" + method.getName());
        return res;
    }
}


class CglibProxyFactory {
    public static Object getProxy(Class<?> clazz) {
        // 创建动态代理增强
        Enhancer enhancer = new Enhancer();
        // 设置类加载器
        enhancer.setClassLoader(clazz.getClassLoader());
        // 设置被代理类
        enhancer.setSuperclass(clazz);
        // 设置方法拦截器
        enhancer.setCallback(new DebugMethodInterceptor());
        return enhancer.create();
    }
}


